const express = require('express');
const { ObjectId } = require('mongodb');
const { getFolderCollection } = require('./database');

const router = express.Router();

// 中间件，用于获取 folderCollection
router.use(async (req, res, next) => {
    req.folderCollection = await getFolderCollection();
    next();
});

// 创建文件夹
router.post('/folders', async (req, res) => {
    try {
        console.log("req.body", req.body);
        const result = await req.folderCollection.insertOne(req.body);
        res.status(201).json({ message: 'Folder created successfully', folderId: result.insertedId });
    } catch (err) {
        console.log(err);
        res.status(500).json({ message: 'Error creating folder', err });
    }
});

// 更新文件夹
router.put('/folders/:id', async (req, res) => {
    try {
        const result = await req.folderCollection.updateOne({ _id: new ObjectId(req.params.id) }, { $set: req.body });
        if (result.matchedCount === 0) {
            return res.status(404).json({ message: 'Folder not found' });
        }
        res.json({ message: 'Folder updated successfully' });
    } catch (err) {
        res.status(500).json({ message: 'Error updating folder', err });
    }
});

// 获取所有文件夹
router.get('/folders', async (req, res) => {
    try {
        const folders = await req.folderCollection.find().toArray();
        res.json(folders);
    } catch (err) {
        res.status(500).json({ message: 'Error fetching folders', err });
    }
});

// 获取特定文件夹
router.get('/folders/:id', async (req, res) => {
    try {
        const folder = await req.folderCollection.findOne({ _id: new ObjectId(req.params.id) });
        if (!folder) {
            return res.status(404).json({ message: 'Folder not found' });
        }
        res.json(folder);
    } catch (err) {
        res.status(500).json({ message: 'Error fetching folder', err });
    }
});

// 删除文件夹
router.delete('/folders/:id', async (req, res) => {
    try {
        const result = await req.folderCollection.deleteOne({ _id: new ObjectId(req.params.id) });
        if (result.deletedCount === 0) {
            return res.status(404).json({ message: 'Folder not found' });
        }
        res.json({ message: 'Folder deleted successfully' });
    } catch (err) {
        res.status(500).json({ message: 'Error deleting folder', err });
    }
});

module.exports = router;